package icu.yougan.youganblogbackend.mapper;

import icu.yougan.youganblogbackend.model.Article;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface ArticleMapper {

    @Select("SELECT a.*, c.name as category_name, u.nickname as author_name " +
            "FROM article a " +
            "LEFT JOIN category c ON a.category_id = c.id " +
            "LEFT JOIN user u ON a.user_id = u.id " +
            "WHERE a.status = 1 " +
            "ORDER BY a.is_top DESC, a.create_time DESC")
    List<Article> selectList();

    @Select("SELECT a.*, c.name as category_name, u.nickname as author_name " +
            "FROM article a " +
            "LEFT JOIN category c ON a.category_id = c.id " +
            "LEFT JOIN user u ON a.user_id = u.id " +
            "WHERE a.id = #{id}")
    Article selectById(Integer id);

    @Select("SELECT a.*, c.name as category_name, u.nickname as author_name " +
            "FROM article a " +
            "LEFT JOIN category c ON a.category_id = c.id " +
            "LEFT JOIN user u ON a.user_id = u.id " +
            "WHERE a.status = 1 AND a.category_id = #{categoryId} " +
            "ORDER BY a.is_top DESC, a.create_time DESC")
    List<Article> selectByCategoryId(Integer categoryId);
    
    @Update("UPDATE article SET view_count = view_count + 1 WHERE id = #{id}")
    void incrementViewCount(Integer id);

    @Insert("INSERT INTO article (title, content, summary, category_id, user_id, view_count, is_top, status) " +
            "VALUES (#{title}, #{content}, #{summary}, #{categoryId}, #{userId}, 0, #{isTop}, 1)")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(Article article);

    @Update("UPDATE article SET title = #{title}, content = #{content}, summary = #{summary}, " +
            "category_id = #{categoryId}, is_top = #{isTop} WHERE id = #{id}")
    void update(Article article);

    @Delete("DELETE FROM article WHERE id = #{id}")
    void deleteById(Integer id);
} 